package net.qhzw.vip.qiyu.service;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import net.qhzw.vip.qiyu.entity.DtsCarRental;
import net.qhzw.vip.qiyu.entity.DtsCarRetreat;
import net.qhzw.vip.qiyu.entity.DtsCarTransfer;
import net.qhzw.vip.qiyu.entity.DtsUser;
import net.qhzw.vip.qiyu.model.IncomeTodayDetails;
import net.qhzw.vip.qiyu.model.WarningQuery;
import net.qhzw.vip.qiyu.util.MyDateUtils;
import net.qhzw.vip.qiyu.util.SecurityUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class SysIndexService {

    @Autowired
    private DtsCarRentalService dtsCarRentalService;

    @Autowired
    private DtsCarTransferService dtsCarTransferService;

    @Autowired
    private DtsCarRetreatService dtsCarRetreatService;

    @Autowired
    private GuaranteeSiteService guaranteeSiteService;

    @Autowired
    private DtsUserBillService dtsUserBillService;

    @Autowired
    private DtsUserService dtsUserService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysCommunityService sysCommunityService;

    /***
     * 查询实名,租车,换车,退车count
     * @return
     */
    public Map<String, Integer> rentalCount(Long shopId) {
        Map<String, Integer> result = new HashMap<>(4);
        Integer authCount = 0;
        Integer rentalCount = 0;
        Integer transferCount = 0;
        Integer retreatCount = 0;
        if (shopId == 1) {
            authCount = dtsUserService.count(new LambdaQueryWrapper<DtsUser>()
                    .eq(DtsUser::getAuthStatus, 1));
        }else {
            //租车
             rentalCount = dtsCarRentalService.count(new LambdaQueryWrapper<DtsCarRental>()
                    .eq(DtsCarRental::getShopId, shopId)
                    .eq(DtsCarRental::getStatus, 2));
            //换车
             transferCount = dtsCarTransferService.count(new LambdaQueryWrapper<DtsCarTransfer>()
                    .eq(shopId != 1, DtsCarTransfer::getShopId, shopId)
                    .eq(DtsCarTransfer::getStatus, 1));
            //退车
            retreatCount = dtsCarRetreatService.count(new LambdaQueryWrapper<DtsCarRetreat>()
                    .eq(shopId != 1, DtsCarRetreat::getShopId, shopId)
                    .eq(DtsCarRetreat::getStatus, 1));
        }
        result.put("authCount", authCount);
        result.put("rentalCount", rentalCount);
        result.put("transferCount", transferCount);
        result.put("retreatCount", retreatCount);
        return result;
    }

    /***
     * 查询担保站点风险预警
     * @param amount
     * @return
     */
    public Map<String, Integer> riskWarning(BigDecimal amount) {
        Long shopId = SecurityUtils.getLoginUser().getShopId();
        //骑遇站点风险预警
        int qyCount = guaranteeSiteService.riskWarningQYCount(amount, shopId);
        WarningQuery query = new WarningQuery();
        query.setUserId(SecurityUtils.getUserId());
        if (amount != null) {
            query.setBalance(amount.toString());
        }
        Map<String, Object> warningMap = sysUserService.getWarningByPage(shopId, query);
        //担保站点风险预警 guarSite
        Map<String, Integer> result = new HashMap<>(2);
        result.put("qyCount", qyCount);
        result.put("guarSiteCount", (int) warningMap.get("count"));
        return result;
    }


    /***
     * 查询租车量
     * @return
     */
    public Map<String, Integer> carRentalCount(Long shopId) {
        Map<String, Integer> carRentalCount = dtsCarRentalService.carRentalCount(shopId);
        return carRentalCount;
    }

    /***
     * 查询今日退车量
     * @return
     */
    public Map<String, Integer> returnAmount(Long shopId) {
        Map<String, Integer> result = dtsCarRetreatService.returnAmount(shopId);
        return result;
    }


    /***
     * 查询今日收入
     * @return
     */
    public BigDecimal queryTodaysIncome(Long shopId) {
        String todaysIncomes = dtsUserBillService.queryTodaysIncome(shopId);
        return new BigDecimal(todaysIncomes).abs();
    }


    /***
     * 查询结余欠款
     * @return
     */
    public BigDecimal balanceArrears(Long shopId) {
        String todaysIncomes = dtsUserService.balanceArrears(shopId);
        return new BigDecimal(todaysIncomes).abs();
    }

    /***
     * 查询维修欠款
     * @return
     */
    public BigDecimal maintArrs(Long shopId) {
        String maintArrs = dtsCarTransferService.maintArrs(shopId);
        BigDecimal bigDecimal = new BigDecimal(maintArrs);
        return bigDecimal.abs();
    }


    /***
     * 导出今日收入明细
     * @param response
     */
    public void exportIncomeTodayDetails(HttpServletResponse response, Long shopId) {
        List<IncomeTodayDetails> incomeTodayDetails = dtsUserBillService.incomeTodayDetails(shopId);
        if (CollectionUtils.isEmpty(incomeTodayDetails)) {
            return;
        }
        //incomeTodayDetails.forEach(data -> data.setDays((int) MyDateUtils.daysBetween(data.getApprovalTime(), new Date())));
        log.info("【今日收入明细】：{}", JSON.toJSONString(incomeTodayDetails, true));
        //导出
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(MyDateUtils.getCurDt() + "收入明细", MyDateUtils.getCurDt()), IncomeTodayDetails.class, incomeTodayDetails);
        try {
            response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode(MyDateUtils.getCurDt() + "收入明细.xls", "UTF-8"));
            ServletOutputStream os = response.getOutputStream();
            workbook.write(os);
            os.close();
            workbook.close();
        } catch (IOException e) {
            log.error("【导出今日收入明细错误】：", JSON.toJSONString(e, true));
        }
    }

}
